package com.lw.leetcode.arr.b;

import java.util.HashMap;
import java.util.Map;

/**
 * arr
 * 128. 最长连续序列
 * 剑指 Offer II 119. 最长连续序列
 *
 * @Author liw
 * @Date 2021/6/16 21:10
 * @Version 1.0
 */
public class LongestConsecutive {

    public static void main(String[] args) {
        LongestConsecutive test = new LongestConsecutive();
        int[] arr = {0, 1};
        int i = test.longestConsecutive(arr);
        System.out.println(i);
    }

    public int longestConsecutive(int[] nums) {
        int length = nums.length;
        if (length == 0) {
            return 0;
        }
        Map<Integer, Integer> map = new HashMap<>(length << 1);
        for (int num : nums) {
            map.put(num, 1);
        }
        int max = 0;
        for (int i = 0; i < length; i++) {
            int num = nums[i];
            Integer value = map.get(num);
            if (value != null) {
                int st = num;
                int end = num;
                while (map.get(++end) != null) {
                    map.put(end, null);
                }
                while (map.get(--st) != null) {
                    map.put(st, null);
                }
                max = Math.max(max, end - st);
            }
        }
        return max - 1;
    }

}
